#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <glib.h>

#include "util.h"

/*
 * 2>&1: redirect stderr to stdout
 * */
GString *shell(const char *cmd) {
	GString *result = g_string_new("");
	char buf[1024];
	FILE *fp;
	if ((fp = popen(cmd, "r")) != NULL) {
		GString *_result = g_string_new("");

		while (fgets(buf, sizeof(buf), fp) != NULL) {
			g_string_append(_result, buf);
		}
		pclose(fp);
		fp = NULL;

		if (!g_utf8_validate(_result->str, -1, NULL)) {
			gchar *utf8 = g_locale_to_utf8(_result->str, -1, 0, 0, 0);
			g_string_append(result, utf8);
			g_free(utf8);
		} else {
			g_string_append(result, _result->str);
		}

		g_string_free(_result, TRUE);
	} else {
		g_string_append_printf(result, "popen %s error.", cmd);
	}
	return result;
}
